package PairedReadFlagStat;

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
require Exporter;
 
@ISA = qw(Exporter AutoLoader);

@EXPORT = qw( readPairedReadFlagStat );

use Data::Dumper;

sub readPairedReadFlagStat {
	my ($dbh, $prefix, $modifier, $field_list) = @_;
	open(FIN, "$prefix.flagstat") || die "cannot open $prefix.flagstat\n";
	my %hash;
	while (<FIN>) {
		my ($val) = split(/ /, $_);
		$hash{$_} = $val;
	}
	close FIN;
	my $RV;
	foreach my $fd (@{$field_list}) {
		my $metric_id = get_metric_id($dbh, $modifier, $fd);
		die "metric_id not found for $modifier $fd\n" unless defined($metric_id);
#		printf STDERR "$fd\t$metric_id\n";
		my $fd_val = "NA";
		foreach my $line (keys %hash) {
			if ($line =~ /$fd/) {
				$fd_val = $hash{$line};
				last;
			}
		}
		$RV->{$metric_id}->{'value'} = $fd_val;
		$RV->{$metric_id}->{'field_name'} = $fd;
	}
	return $RV;
}

sub get_metric_id {
	my ($dbh, $modifier, $fd) = @_;
	my $sql = "select Metric_id from MetricInfo where Field_name = \"$fd\" and Modifier = \"$modifier\"";
	return fetchrow1col1_arrayref($dbh, $sql);
}

sub fetchrow1col1_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchrow_arrayref();
  $sh->finish();
  return $ary_ref->[0];
}

sub my_fetchall_arrayref {
  my ($dbh, $sql) = @_;
  my $sh = $dbh->prepare($sql);
  $sh->execute();
  my $ary_ref = $sh->fetchall_arrayref();
  $sh->finish();
  return $ary_ref;
}

1;
# 18154060 in total
# 0 QC failure
# 0 duplicates
# 17739969 mapped (97.72%)
# 18154060 paired in sequencing
# 9077030 read1
# 9077030 read2
# 17460016 properly paired (96.18%)
